<?php

class StocksController extends AppController {

    public $sl_stocks = array(
        'actions' => array('V' => 'view', 'E' => 'edit', 'D' => 'delete'),
        'filters' => array(
            array('name' => 'Stock.tipo_id', 'label' => 'Tipo Producto', 'presentation' => 'SELECT', 'classparams' => '{"model":"Tipo"}'),
            array('name' => 'Stock.producto', 'label' => 'Nombre Producto')
        ),
        'columns' => array(
            array('name' => 'Stock.tipo_id', 'label' => 'Tipo Producto', 'presentation' => 'SELECT', 'classparams' => '{"model":"Tipo"}'),
            array('name' => 'Stock.producto', 'label' => 'Nombre Producto'),
            array('name' => 'Stock.cantidad', 'label' => 'Cantidad Disponible')
        )
    );
    public $maint_stocks = array(
        'fields' => array(
            'Descripción del Stock' => array(
                array('name' => 'tipo_id', 'label' => 'Tipo Producto', 'presentation' => 'SELECT', 'classparams' => '{"model":"Tipo"}'),
                array('name' => 'producto', 'label' => 'Nombre Producto'),
                array('name' => 'cantidad', 'label' => 'Cantidad Disponible')
            )
        )
    );

    public function isAuthorized() {
        if ($this->action === 'disponibles') {
            return true;
        }
        return parent::isAuthorized();
    }

    public function add() {
        $this->maint = $this->maint_stocks;
        parent::add();
    }

    public function edit($id = null) {
        $this->maint = $this->maint_stocks;
        parent::edit($id);
    }

    public function index() {
        $this->search_list = $this->sl_stocks;
        parent::index();
    }

    public function view($id = null) {
        $this->maint = $this->maint_stocks;
        parent::view($id);
    }

    public function disponibles($tipo_id) {
        if (!$this->request->is('get')) {
            throw new MethodNotAllowedException();
        }

        $model = $this->getModelName();

        $this->$model->Tipo->id = $tipo_id;
        if (!$this->$model->Tipo->exists()) {
            throw new NotFoundException(__('Registro inexistente'));
        }

        $data = $this->$model->find('all', array('conditions' => array('tipo_id' => $tipo_id, 'cantidad' > 0)));

        $this->set('data', json_encode($data));
        return $this->render('/ajax', 'ajax');
    }

}